# -*-coding:utf-8-*-
import gevent
import logging
import json
from gevent import socket, monkey
import jsonrpclib


class collectTcpService(object):
    # 初始化
    # config:配置文件
    # port：端口
    # msg_type:3个字节的消息类型，CLA:空净消息，MON：环境监控
    def __init__(self):
        self.listenPort = 8000
        self.odoo_protocol="http"
        self.odoo_db_name="watermeter"
        self.odoo_db_pwd="odoo"
        self.odoo_db_user="odoo"
        self.odoo_host="127.0.0.1"
        self.odoo_Port="8069"
        self.uid=None

        #转化协程
        monkey.patch_all()

        #初始化数据库连接

    def start(self):
        try:
            # 开始监听
            print self.listenPort
            print "-------------"
            s = socket.socket()
            s.bind(('', self.listenPort))
            s.listen(200)
            print ("start listen")
            while True:
                cli, addr = s.accept()
                gevent.spawn(self.handle_request, cli)

        except Exception as ex:
            print ex.message

    def handle_request(self,conn):
        while True:
            data = conn.recv(20480)
            try:
                if not data:
                    conn.close()
                    break
                startx = data.index("{")
                endx = data.index("}", -1)
                msg=data[startx:endx+1]

                dict1=json.loads(msg)
                data=json.dumps(dict1)
                print data
                self.odoo_invoke('watermeters.test','subscribecallback',data)

            except Exception as ex:
                print '----error---------------:'
                print ex.message

    def odoo_invoke(self, model, method, *args):
        try:
            if self.uid == None:
                odoo_url = "%s://%s:%s/jsonrpc" % (self.odoo_protocol, self.odoo_host, self.odoo_Port)
                print odoo_url
                self.server = jsonrpclib.Server(odoo_url)
                self.uid = self.server.call(service="common", method="login",
                                            args=[self.odoo_db_name, self.odoo_db_user, self.odoo_db_pwd])

            args = [self.odoo_db_name, self.uid, self.odoo_db_pwd, model, method] + list(args)
            self.server.call(service="object", method="execute", args=args)
            return {"err_code": 0, "err_msg": ""}
        except Exception as ex:
            print ex.message
            return {"err_code": 1, "err_msg": "service Error"}



if __name__ == "__main__":

    cj = collectTcpService()
    cj.start()
